<template>
  <el-dialog
    v-model="createVisible"
    :title="operation == 'create' ? '添加商品规格' : '编辑商品规格'"
    @before-ok="createOk"
    @close="close(createRef)"
    width="1000px"
    top="100px"
  >
    <div style="width: 900px">
      <el-form
        :model="createForm"
        ref="createRef"
        :rules="createRules"
        label-width="130px"
        size="default"
        v-loading="initLoading"
      >
        <el-form-item label="规格模板名称：" prop="spec_temp_name">
          <el-input
            v-model="createForm.spec_temp_name"
            placeholder="请输入规格模板名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="规格属性：">
          <div class="flex">
            <el-input
              class="form-main-item-small"
              placeholder="请输入规格名"
              v-model="specName"
            >
            </el-input>
            <el-button
              class="ml10"
              type="primary"
              bg
              text
              @click="createSpecName"
              >添加规格</el-button
            >
          </div>
        </el-form-item>
        <el-form-item>
          <storeGoodsSpec
            v-model="createForm.attrs"
            ref="storeGoodsSpecRef"
          ></storeGoodsSpec>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="flex center">
        <el-button @click="close(createRef)">取消</el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          :disabled="btnLoading"
          @click="createOk(createRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
    
    <script lang="ts">
export default {
  name: "storeGoodsSpecTemplatesCreate",
};
</script>
    <script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, reactive } from "vue";
import type { FormInstance } from "element-plus";
import storeGoodsSpec from "@/components/goods-spec/index.vue";
import {
  getGoodsSpecTemplatesDetail,
  createGoodsSpecTemplates,
  updateGoodsSpecTemplates,
} from "@/api/store/goods_spec_templates";
import type { Result, ResultError } from "@/types";
import { forEach } from "lodash";

const {
  proxy,
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["success"]);

const createVisible = ref<boolean>(false);

const operation = ref<string>("create");

const operationId = ref<number>(0);

const createRef = ref<typeof FormInstance>();

const createForm = ref<any>({
  spec_temp_name: "",
  attrs: [],
});
const createRules: any = reactive({
  spec_temp_name: [{ required: true, message: "规格模板名称不能为空！" }],
});

const btnLoading = ref<boolean>(false);

const initLoading = ref<boolean>(true);

const toInit = () => {
  if (!operationId.value) {
    initLoading.value = false;
    return;
  }
  getGoodsSpecTemplatesDetail({ id: operationId.value })
    .then((res: Result) => {
      createForm.value.spec_temp_name = res.data.spec_temp_name;
      createForm.value.attrs = res.data.attrs;
      proxy?.$refs["storeGoodsSpecRef"].refresh(res.data.attrs);
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const specName = ref<string>("");

const createSpecName = () => {
  if (specName.value == "") {
    $utils.errorMsg("请输入规格名");
    return false;
  }
  if (specName.value.indexOf(" ") !== -1) {
    $utils.errorMsg("规格名不能包含空格");
    return false;
  }
  createForm.value.attrs.push({
    name: specName.value,
    value: [],
  });
  specName.value = "";
};

const createOk = async (formEl: typeof FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      if (createForm.value.attrs.length == 0) {
        $utils.errorMsg("请至少添加一条商品规格！");
        return false;
      }
      var isError = false;
      createForm.value.attrs.forEach(
        (item: { value: string[]; name: string }) => {
          if (item.value.length == 0) {
            $utils.errorMsg("规格规格值不能为空！");
            isError = true;
          }
        }
      );
      if (isError || btnLoading.value) {
        return false;
      }
      btnLoading.value = true;
      let operationApi: any = null;
      if (operation.value == "create") {
        operationApi = createGoodsSpecTemplates(createForm.value);
      } else {
        operationApi = updateGoodsSpecTemplates(
          Object.assign(
            {
              id: operationId.value,
            },
            createForm.value
          )
        );
      }
      operationApi
        .then((res: Result) => {
          $message.success(res.message);
          close(formEl);
          emit("success");
          btnLoading.value = false;
        })
        .catch((err: ResultError) => {
          $utils.errorMsg(err);
          btnLoading.value = false;
        });
    }
  });
};

const storeGoodsSpecRef = ref<HTMLElement>();

const open = (id: number = 0) => {
  initLoading.value = true;
  if (id != 0) {
    operation.value = "update";
    operationId.value = id;
  } else {
    operation.value = "create";
  }
  nextTick(() => {
    toInit();
  });
  createVisible.value = true;
};

const close = async (formEl: typeof FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields();
  }
  createForm.value.attrs = [];
  operationId.value = 0;
  createVisible.value = false;
  proxy?.$refs["storeGoodsSpecRef"].refresh();
};

defineExpose({ open });
</script>